package org.openkoala.koala.popup.preference;

import java.io.File;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.openkoala.koala.config.DBConfigService;
import org.openkoala.koala.config.vo.DBConfigVO;
import org.openkoala.koala.console.ConsoleFactory;
import org.openkoala.koala.exception.KoalaException;
import org.openkoala.koala.popup.BaseAction;
import org.openkoala.koala.util.ProjectQueryUtil;
import org.openkoala.koala.widget.Project;

/**
 * 右键点击“Preferences”时运行的action
 * @author xmfang
 *
 */
public class ProjectPreferenceAction extends BaseAction {

	private String projectPath;
	
	@Override
	public void run(IAction arg0) {
		ConsoleFactory.showConsole();
		initProjectPath();
		if (projectPath == null) {
			return;
		}

		ProjectPreferenceDialog projectPreferenceDialog = new ProjectPreferenceDialog(shell, projectPath, this);
		projectPreferenceDialog.open();
	}

	private void initProjectPath() {
		try {
			String selectedPath = getResource().getLocationURI().getPath();
			Project project = ProjectQueryUtil.getProject(selectedPath);
			projectPath = project.getPath() + File.separatorChar + project.getAppName();
		} catch (KoalaException e) {
			popupErrorMessage(e.getMessage());
			e.printStackTrace();
		}
	}
	
	void updateProjectDatabasePreference(DBConfigVO dbConfigVO, boolean isTestDbConfig) {
		try {
			if (isTestDbConfig) {
				DBConfigService.updateTestDBConfig(projectPath, dbConfigVO);
			} else {
				DBConfigService.updateDBConfig(projectPath, dbConfigVO);
			}
		} catch (KoalaException e) {
			popupErrorMessage(e.getMessage());
			e.printStackTrace();
		}
	}
	
	void refreshProject() {
		try {
			getResource().refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

}
